<template>
  <view class="page ui-form-basic page-carriage-form">
    <page-header :showPlaceHolder="false" :customTitle="customTitle"></page-header>
    <fui-form ref="formRef" :model="form" class="form-wrapper" :top="store.getters.topHeight" labelWidth="160" labelSize="28" labelWeight="bold">
      <view class="carriage-form-block">
        <fui-form-item label="模板名称" prop="name" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-input size="28" :padding="[0]" :borderBottom="false" :maxlength="20" placeholder="请输入模板名称" v-model="form.name"></fui-input>
        </fui-form-item>
        <fui-form-item label="计费方式" prop="chargeMode" left="0" marginTop="14" :padding="['16rpx', 0]">
          <fui-radio-group class="carriage-cost-methods" name="radio" v-model="form.chargeMode" @change="onChangeCostMethod">
            <fui-label v-for="(obj, key) in CARRIAGE_COST_METHODS" :key="key">
              <fui-radio :disabled="!!carriageId" :value="key + ''" scaleRatio="0.8" color="#FF2B2B"></fui-radio> <fui-text :text="obj.name" size="24"></fui-text>
            </fui-label>
          </fui-radio-group>
        </fui-form-item>
      </view>
      <view class="carriage-form-block">
        <fui-form-item label="默认运费" prop="defaultCarriage" left="0" marginTop="14" :padding="['16rpx', 0]" @click="showCarriageDefaultPopup" arrow>
          <fui-text v-if="form.defaultCarriage" :text="formatCarriageText(form.defaultCarriage)" size="24" color="#333"></fui-text>
          <fui-input v-else size="28" :padding="[0]" :borderBottom="false" :maxlength="20" placeholder="请选择" v-model="form.defaultCarriage" disabled></fui-input>
        </fui-form-item>
        <view class="carriage-area-wrapper">
          <view class="carriage-area-header">
            <view class="carriage-area-title">
              <fui-text text="指定地区运费(可选)" size="28" fontWeight="bold" :padding="['10rpx', 0]"></fui-text>
              <fui-text text="添加" size="24" color="var(--fui-color-primary)" @click="handleAddItem"></fui-text>
            </view>
            <view><fui-text text="除指定地区外，其余地区运费采用：“默认运费”，指定区域之间如有覆盖地区数据，将取首件价格最低项作为最终的运费计算方式。" size="24" color="#999"></fui-text></view>
          </view>
          <view class="carriage-area-list">
            <view class="carriage-area-item" :class="{'is-shake': showError && (!item.areaText || !item.startCount)}" v-for="(item, index) in areaCarriageList" :key="index">
              <view class="carriage-area-text" v-if="item.areaText"><fui-text :text="item.areaText" size="24" color="#333" fontWeight="bold"></fui-text></view>
              <view class="carriage-area-text" v-else><fui-text text="请添加地区信息" size="24" color="#333" fontWeight="bold"></fui-text></view>
              <view class="carriage-area-text" v-if="item.startCount"><fui-text :text="formatCarriageText(item)" size="24" color="#333"></fui-text></view>
              <view class="carriage-area-text" v-else><fui-text text="请设置运费" size="24" color="#333"></fui-text></view>
              <view class="carriage-area-tools">
                <fui-button plain width="140rpx" height="48rpx" borderColor="#ddd" radius="24rpx" :margin="[0, '10rpx']" color="#333" size="24" @click="showAreaItemPopup(index)">{{ item.areaText ? '修改地区' : '添加地区' }}</fui-button>
                <fui-button plain width="140rpx" height="48rpx" borderColor="#ddd" radius="24rpx" :margin="[0, '10rpx']" color="#333" size="24" @click="showCarriageItemPopup(item, index)">{{ item.startCount ? '修改运费' : '设置运费' }}</fui-button>
                <fui-button plain width="100rpx" height="48rpx" borderColor="#ddd" radius="24rpx" :margin="[0, '10rpx']" color="#333" size="24" @click="handleDeleteItem(index)">删除</fui-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </fui-form>

    <view class="btn-wrapper">
      <fui-button class="ui-btn-primary_plain" text="取消" height="78rpx" radius="8rpx" :margin="['0', '54rpx', '0', '0']" @click="tab.navigateBack"></fui-button>
      <fui-button text="确认" height="78rpx" radius="8rpx" :margin="['0']" @click="handleSubmit"></fui-button>
    </view>

    <set-carriage ref="carriageDefaultRef" :chargeMode="form.chargeMode" @submit="onSetCarriageDefault"></set-carriage>
    <set-carriage ref="carriageItemRef" :chargeMode="form.chargeMode" @submit="onSetCarriageItem"></set-carriage>
    <multilevel-picker ref="rangePickerRef" :data="rangeData" :defaultProps="rangeProps" @submit="onSetAreaItem"></multilevel-picker>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import pageHeader from '@/components/header'
import SetCarriage from './setCarriage'
import multilevelPicker from '@/components/multilevel'
import { CARRIAGE_COST_METHODS } from './consts'
import systemApi from '@/api/system'
import carriageApi from '@/api/carriage'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const customTitle = ref('新建运费模板')
const carriageId = ref('')
onLoad((option) => {
  if (store.getters.regionData.length) {
    rangeData.value = store.getters.regionData
  } else {
    getRangeList()
  }
  if (option.id) {
    customTitle.value = '编辑运费模板'
    carriageId.value = option.id
    getCarriageDetail()
  }
})

// 运费模板表单信息
const formRef = ref(null)
const form = ref({
  payMode: '11',
  chargeMode: '21'
})
const rules = [
  {
    name: 'name',
    rule: ['required', 'isSpecial'],
    msg: ['请输入模板名称', '模板名称不允许输入特殊字符']
  },
  {
    name: 'chargeMode',
    rule: ['required'],
    msg: ['请选择计费方式']
  },
  {
    name: 'defaultCarriage',
    rule: ['required'],
    msg: ['请选择默认运费']
  }
]

// 默认运费设置
const carriageDefaultRef = ref(null)
const showCarriageDefaultPopup = () => {
  carriageDefaultRef.value.show(form.value.defaultCarriage)
}
const onSetCarriageDefault = (data) => {
  form.value.defaultCarriage = data
}
const onChangeCostMethod = () => {
  if (!carriageId.value) {
    delete form.value.defaultCarriage
  }
}

// 指定区域运费操作
const showError = ref(false)
let currentCarriageIndex = 0
const areaCarriageList = ref([])
const handleAddItem = () => {
  areaCarriageList.value.push({})
}
const handleDeleteItem = (index) => {
  areaCarriageList.value.splice(index, 1)
}

// 运费模板信息
const getCarriageDetail = () => {
  modal.loading('加载中...')
  try{
    carriageApi.getCarriageDetail(carriageId.value).then(res => {
      modal.closeLoading()
      if (res.code === 0 && res.data) {
        form.value = {
          ...res.data,
          payMode: res.data.payMode + '',
          chargeMode: res.data.chargeMode + '',
          defaultCarriage: res.data.freightTemplateCharges[0]
        }
        areaCarriageList.value = res.data.freightTemplateCharges.slice(1)

      } else {
        modal.msgError(res.msg)
      }
    })
  }catch(err){
    modal.closeLoading()
    modal.msgError(err)
  }
}

// 添加指定区域
const rangeData = ref([])
const rangePickerRef = ref(null)
const rangeProps = {
	text: 'name',
	value: 'id',
	children: 'children'
}
const getRangeList = () => {
	systemApi.administration().then((res) => {
		if (res.code == 0) {
			rangeData.value = res.data
		}
	})
}
const showAreaItemPopup = (index) => {
  currentCarriageIndex = index
	rangePickerRef.value.show()
}
const onSetAreaItem = (data) => {
  showError.value = false
  areaCarriageList.value[currentCarriageIndex].areaText = data.text
  areaCarriageList.value[currentCarriageIndex].areaIds = data.value
}

// 指定地区运费设置
const carriageItemRef = ref(null)
const showCarriageItemPopup = (item, index) => {
  currentCarriageIndex = index
  carriageItemRef.value.show(item)
}
const onSetCarriageItem = (data) => {
  showError.value = false
  areaCarriageList.value[currentCarriageIndex] = {
    ...areaCarriageList.value[currentCarriageIndex],
    ...data
  }
}

// 校验指定地区运费设置
const validatorCarriageList = () => {
  let isValid = true
  const emptyObj = areaCarriageList.value.find(item => !item.areaText || !item.startCount)
  if (!!emptyObj) {
    showError.value = true
    isValid = false
    modal.msgError('指定区域运费设置不完整，请检查！')
  } else {
    showError.value = false
  }
  return isValid
}

// 提交表单方法
const handleSubmit = async () => {
  const validRes = await formRef.value.validator(form.value, rules)
  if (validRes.isPassed) {
    const validList = validatorCarriageList()
    if (!validList) {
      return
    }
    const { userType, companyId } = store.getters
    const formData = {
      ...form.value,
      supplierId: userType === '2' ? companyId : '',
      freightTemplateCharges: [
        form.value.defaultCarriage,
        ...areaCarriageList.value
      ]
    }
    const apiUrl = form.value.id ? 'updateCarriage' : 'addCarriage'
    carriageApi[apiUrl](formData).then((res) => {
      if (res.code === 0) {
        modal.msg(`运费模板已${form.value.id ? '修改' : '添加'}！`)
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msgError(res.msg)
      }
    })
  }
}

// 格式化运费计费方式
const formatCarriageText = (obj) => {
  return `${obj.startCount}${CARRIAGE_COST_METHODS[form.value.chargeMode].unit}以内${obj.startPrice}元，每增加${obj.extraCount}${CARRIAGE_COST_METHODS[form.value.chargeMode].unit}，运费增加${obj.extraPrice}元。`
}
</script>

<style lang="scss" scoped>
@import "@/static/scss/form.scss";

.page-carriage-form {
  .form-wrapper {
    background-color: #f8f8f8;
    padding: 0 !important;
  }
  .carriage-form-block {
    overflow: hidden;
    border-radius: 8rpx;
    background-color: #fff;
    margin-bottom: 32rpx;
    padding: 0 24rpx 36rpx;
  }
  .carriage-cost-methods {
    display: flex;
    .fui-label__box {
      margin-right: 32rpx !important;
      font-size: 0;
      .fui-radio__input {
        margin-right: 16rpx;
      }
    }
  }
  .carriage-area-wrapper {
    background-color: #fff;
    margin-top: 24rpx;
    .carriage-area-header {
      .carriage-area-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
    .carriage-area-list {
      margin-top: 32rpx;
      .carriage-area-item {
        background-color: #fafafa;
        border-radius: 8rpx;
        margin-top: 16rpx;
        padding: 24rpx;
        &.is-shake {
          border: 2rpx solid #ff2b2b;
        }
        .carriage-area-text {
          margin-bottom: 10rpx;
        }
        .carriage-area-tools {
          display: flex;
          justify-content: flex-end;
          border-top: 2rpx solid #eee;
          margin-top: 32rpx;
          padding-top: 32rpx;
        }
      }
    }
  }
}
</style>
